package com.deuwise.system.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.deuwise.common.validator.ValidatorUtils;
import com.deuwise.common.validator.group.UpdateGroup;
import com.deuwise.system.entity.SysUser;
import com.deuwise.system.entity.message.MessageDo;
import com.deuwise.system.entity.message.MessageSendDo;
import com.deuwise.system.service.MessageSendService;
import com.deuwise.system.service.SysUserService;
import com.deuwise.system.service.message.MessageDoService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@Api(description = "消息内容管理接口",tags = "消息模块")
@RequestMapping("/api/message")
@RequiresAuthentication
public class MessageController extends AbstractController {


    @Autowired
    private SysUserService userService;

    @Autowired
    private MessageDoService messageDoService;

    @Autowired
    private MessageSendService sendService;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加消息")
    public Result<Object> addMessage(MessageDo message){

        message.setCreateTime(new Date());
        message.setCreateUser(getUserId());
        boolean add = messageDoService.insert(message);
        if(add) {
            // 保存消息发送表
            List<MessageSendDo> messageSends = new ArrayList<>();
            if (message.getRange().equals(1)) {
                // 全体
                List<SysUser> allUser = userService.selectList(null);
              allUser.forEach(u->{
                  MessageSendDo ms = new MessageSendDo();
                ms.setMessageId(message.getId());
                ms.setUserId(u.getId());
                messageSends.add(ms);
             });
                // 推送
                messagingTemplate.convertAndSend("/topic/subscribe", "您收到了新的系统消息");
            } else {
                // 指定用户
                for (String id : message.getUserIds()) {
                    MessageSendDo ms = new MessageSendDo();
                ms.setMessageId(message.getId());
                ms.setUserId(id);
                messageSends.add(ms);
                    // 指定用户
                    messagingTemplate.convertAndSendToUser(id, "/queue/subscribe", "您收到了新的消息");
                }
            }
            sendService.insertOrUpdateBatch(messageSends);
        }

        return Result.ok("添加成功");
    }
    @ApiOperation(value = "获取list", notes = "获取list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<MessageDo>> list(MessageDo messageDo){
        Wrapper<MessageDo> wrapper = new EntityWrapper<MessageDo>();
        if(messageDo!=null){
            if(StringUtils.isNotBlank(messageDo.getTitle())){
                wrapper.like("title",messageDo.getTitle());
            }
            if(StringUtils.isNotBlank(messageDo.getContent())){
                wrapper.like("content",messageDo.getContent());
            }

            if(StringUtils.isNotBlank(messageDo.getStartDate())){
                wrapper.ge("create_time",messageDo.getStartDate());
            }
            if(StringUtils.isNotBlank(messageDo.getEndDate())){
                wrapper.le("create_time",messageDo.getEndDate());
            }
        }
        wrapper.orderBy("create_time",false);
        Page<MessageDo> sysDictPage = messageDoService.selectPage(getPage(MessageDo.class),wrapper);
        return Result.ok(sysDictPage);
    }




    @RequestMapping(value = "/getSendList", method = RequestMethod.GET)
    @ApiOperation(value ="获取发送记录")
    public Result<Page<MessageSendDo>> getSendList(MessageSendDo ms
                                                     ) {
        Wrapper<MessageSendDo> wrapper = new EntityWrapper<MessageSendDo>();
        if (ms != null) {
            if (StringUtils.isNotBlank(ms.getUserId())) {
                wrapper.like("user_id", ms.getUserId());
            }
            if (StringUtils.isNotBlank(ms.getMessageId())) {
                wrapper.like("message_id", ms.getMessageId());
            }

        }
        Page<MessageSendDo> page = sendService.selectPage(getPage(MessageSendDo.class), wrapper);
        // lambda
        page.getRecords().forEach(item -> {
            SysUser u = userService.selectById(item.getUserId());
            item.setUserName(u.getUsername());
            MessageDo m = messageDoService.selectById(item.getMessageId());
            item.setTitle(m.getTitle());
            item.setContent(m.getContent());
            item.setType(m.getType());
        });
        return Result.ok(page);
    }
    @ApiOperation("修改发送消息状态")
    @PutMapping("/updateSendStatus")
    public R update(@RequestBody MessageSendDo messageDo) {
        ValidatorUtils.validateEntity(messageDo, UpdateGroup.class);
        sendService.updateById(messageDo);

        return R.ok();
    }

    @ApiOperation("修改消息")
    @PutMapping("")
    public R update(@RequestBody MessageDo messageDo) {
        ValidatorUtils.validateEntity(messageDo, UpdateGroup.class);
        messageDoService.updateById(messageDo);

        return R.ok();
    }


    @ApiOperation(value = "批量删除记录")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.POST)
    public R deleteSelect(@ApiParam(value = "ids集合", name = "ids", required = true) @RequestParam String[] ids) {
        //消息类型进行判断不允许删除的消息类型
        try {
            if (ids != null && ids.length > 0) {
                messageDoService.deleteBatchIds(Arrays.asList(ids));
            }
        } catch (Exception ex) {
            return R.error("删除失败");
        }
        return R.ok();
    }

    @ApiOperation("删除消息")
    @DeleteMapping("/{messageId}")
    public R delete(@PathVariable("messageId") String messageId) {
        //消息类型进行判断不允许删除的消息类型
        messageDoService.deleteById(messageId);
        return R.ok();
    }
}
